import { getUserInfo, logout } from '@/api/user'

const user = {
  state: {
    token: localStorage.getItem('token') || '',
    userName: '',
    permissions: []
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      localStorage.setItem('token', token)
    },
    SET_USER_NAME: (state, userName) => {
      state.userName = userName
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    CLEAR_USER_INFO: (state) => {
      state.token = ''
      state.userName = ''
      state.permissions = []
      localStorage.removeItem('token')
    }
  },
  actions: {
    // 获取用户信息
    getUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(response => {
          const { userName, permissions } = response.data
          commit('SET_USER_NAME', userName)
          commit('SET_PERMISSIONS', permissions)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    
    // 退出登录
    logout({ commit }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('CLEAR_USER_INFO')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
